import json, csv
import pandas as pd
import pickle
from datetime import timedelta, datetime
from django.shortcuts import render
from django.http import HttpResponseRedirect
from userapp.views import get_user_cls
from userapp.models import *
from app.models import *

def HomeCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    page = request.GET.get("page")
    if page:
        page = int(page)
    else:
        page = 1
    pageSize = request.GET.get("pageSize")
    if pageSize:
        pageSize = int(pageSize)
    else:
        pageSize = 100
    shoptab = ShopTab.objects.all()
    totalNum = len(shoptab)
    shoptab = shoptab[(page - 1) * pageSize:page * pageSize]
    data_list = []
    num = (page - 1) * pageSize + 1
    for data in shoptab:
        data_list.append({
            "num": num,
            "shopId": data.id,
            "name": data.name,
            "sku": data.sku,
            "sales": data.sales
        })
        num = num + 1
    res_data["data"]["totalNum"] = totalNum
    res_data["data"]["page"] = page
    res_data["data"]["dataList"] = data_list
    return render(request, 'home.html', res_data)

def SaleCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    shopPage = request.GET.get("shopPage")
    if shopPage:
        shopPage = int(shopPage)
    else:
        shopPage = 1
    shopId = request.GET.get("shopId")
    producttab = ProductTab.objects.filter(shop=shopId)
    num = 1
    data_list = []
    for data in producttab:
        data_list.append({
            "num": num,
            "shop": data.shop.name,
            "price": data.price,
            "model": data.model,
            "size": data.size,
            "sales": data.sales,
            "product": data.product,
            "evaluate": data.evaluate
        })
        num = num + 1
    res_data["data"]["shopPage"] = shopPage
    res_data["data"]["dataList"] = data_list
    return render(request, 'sale.html', res_data)

def FxCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    op = request.GET.get("op")
    if not op:
        op = "one"
    if op == "one":
        shoptab = ShopTab.objects.all().order_by("-sales")[0:20]
        shop_name_list = []
        shop_sale_list = []
        for data in shoptab:
            shop_name_list.append(data.name)
            shop_sale_list.append(data.sales)
        res_data["data"]["shop_name_list"] = json.dumps(shop_name_list)
        res_data["data"]["shop_sale_list"] = json.dumps(shop_sale_list)

        producttab = ProductTab.objects.all()
        data_dict = {}
        for data in producttab:
            size = data.size
            price = data.price
            sales = data.sales
            if size not in data_dict:
                data_dict[size] = {
                    "price": price*sales,
                    "sales": sales
                }
            else:
                data_dict[size]["price"] = data_dict[size]["price"] + price*sales
                data_dict[size]["sales"] = data_dict[size]["sales"] + sales
        size_list = []
        price_list = []
        sale_list = []
        for size in ['0.5匹','1匹','1.2匹','1.5匹','2匹','2.5匹','3匹','4匹','5匹','6匹']:
            data = data_dict[size]
            size_list.append(size)
            price = data["price"]
            sale = data["sales"]
            price_list.append(price)
            sale_list.append(sale)
        res_data["data"]["size_list"] = json.dumps(size_list)
        res_data["data"]["price_list"] = json.dumps(price_list)
        res_data["data"]["sale_list"] = json.dumps(sale_list)
        return render(request, 'fxOne.html', res_data)
    elif op == "two":
        topList = []
        bottomList = []
        producttab = ProductTab.objects.all().order_by("-sales")
        num = 1
        for data in producttab[0:20]:
            topList.append({
                "num": num,
                "shop": data.shop.name,
                "price": data.price,
                "model": data.model,
                "size": data.size,
                "sales": data.sales,
                "product": data.product,
                "evaluate": data.evaluate
            })
            num = num + 1

        num = 1
        producttab = ProductTab.objects.all().order_by("sales")
        for data in producttab[0:20]:
            bottomList.append({
                "num": num,
                "shop": data.shop.name,
                "price": data.price,
                "model": data.model,
                "size": data.size,
                "sales": data.sales,
                "product": data.product,
                "evaluate": data.evaluate
            })
            num = num + 1
        res_data["data"]["topList"] = topList
        res_data["data"]["bottomList"] = bottomList
        return render(request, 'fxTwo.html', res_data)
    elif op == "three":
        date_list = []
        sale_list = []
        # 打开CSV文件
        with open('data/sale.csv', 'r') as file:
            # 创建一个CSV字典读取器对象
            reader = csv.DictReader(file)

            # 遍历CSV文件的每一行
            for row in reader:
                # 打印每一行的内容，其中每一行都是一个字典
                Year = row["Year"]
                Month = row["Month"]
                Day = row["Day"]
                sales = row["Sales"]
                date_list.append(f"{Year}-{Month}-{Day}")
                sale_list.append(int(sales))
        start_date = date_list[-1]
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        # 加载模型
        with open('data/model/model.pkl', 'rb') as file:
            sale_model = pickle.load(file)
        res_data["data"]["leftLen"] = len(sale_list)
        res_data["data"]["startX"] = date_list[-1]
        for i in range(7):
            start_date += timedelta(days=1)
            y = start_date.year
            m = start_date.month
            d = start_date.day
            date_list.append(start_date.strftime('%Y-%m-%d'))
            prediction = sale_model.predict(pd.DataFrame({'Year': [y], 'Month': [m], 'Day': [d]}, dtype=float))
            sale_list.append(int(prediction[0]))
        res_data["data"]["endX"] = date_list[-1]
        print(date_list)
        res_data["data"]["dateList"] = json.dumps(date_list)
        res_data["data"]["saleList"] = json.dumps(sale_list)
        print(sale_list)
        return render(request, 'fxThree.html', res_data)
    return render(request, 'fxOne.html', res_data)